﻿using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System;
using System.ServiceModel;
using System.Windows;
using ConsoleClient;
namespace INTEXReportSrv
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public IDisposable SignalR { get; set; }
        const string ServerURI = "http://192.168.31.119:25008";
        public static log4net.ILog log = log4net.LogManager.GetLogger(
   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        ServiceHost host;
        public MainWindow()
        {
            try
            {
                /*
                ITXCLIENT client = new ITXCLIENT();
                client.Server = "220.180.51.106";
                client.Port = 25002;
                client.Connect();
                client.Commnicate("HR20", "I"); */
                log.Info("Start  InitializeComponent");
                InitializeComponent();
                log.Info("End InitializeComponent");
                this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
                this.Unloaded += new RoutedEventHandler(MainWindow_Unloaded);
            }
            catch(Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }

        void MainWindow_Unloaded(object sender, RoutedEventArgs e)
        {
            if (host != null)
                host.Close();
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                host = new ServiceHost(typeof(IntexReptServBL));
                //host = new ServiceHost(typeof(IntexReptServBL), new Uri("http://localhost:25004/"));
                log.Info("Host is New");
                host.Open();
                //ServiceHost crossDomainserviceHost = new ServiceHost(typeof(DomainService));
                //crossDomainserviceHost.Open();
                log.Info(host.ToString());
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
            }
        }
        private Thread _listenthread;
        private void ButtonStart_Click(object sender, RoutedEventArgs e)
        {
            WriteToConsole("Starting server...");
            ButtonStart.IsEnabled = false;
            _listenthread = new Thread(StartServer);
            _listenthread.Start();
            //Task.Run(() => StartServer());
        }

        /// <summary>
        /// Stops the server and closes the form. Restart functionality omitted
        /// for clarity.
        /// </summary>
        private void ButtonStop_Click(object sender, RoutedEventArgs e)
        {
            SignalR.Dispose();
            Close();
        }

        /// <summary>
        /// Starts the server and checks for error thrown when another server is already 
        /// running. This method is called asynchronously from Button_Start.
        /// </summary>
        private void StartServer()
        {
            try
            {
                SignalR = WebApp.Start(ServerURI);
            }
            catch (TargetInvocationException)
            {
                WriteToConsole("A server is already running at " + ServerURI);
                this.Dispatcher.Invoke(() => ButtonStart.IsEnabled = true);
                return;
            }
            this.Dispatcher.Invoke(() => ButtonStop.IsEnabled = true);
            WriteToConsole("Server started at " + ServerURI);
        }
        public void WriteToConsole(String message)
        {
            if (!(RichTextBoxConsole.CheckAccess()))
            {
                this.Dispatcher.Invoke(() =>
                    WriteToConsole(message)
                );
                return;
            }
            RichTextBoxConsole.AppendText(message + "\r");
        }
    }
}
